import { Component, OnInit, HostListener } from '@angular/core'
import { Router, NavigationEnd } from '@angular/router'
import { Store } from '@ngrx/store'

import * as fromRoot from '../../core/reducers'
import * as fromChecklist from '../../core/actions/checklist'

import { IList, ITask, IUser } from '../../core/models'
import { INewListDto } from '../../core/dtos'
import { Functions } from '../../common/functions'
@Component({
  selector: 'app-sider',
  templateUrl: './sider.component.html',
  styleUrls: ['./sider.component.less']
})
export class SiderComponent implements OnInit {
  currentUrl: string
  currentUser: IUser
  menuItems: IList[]
  myDayTasks: ITask[]
  unFinishedCount: number

  contextmenuItem: IList
  contextmenuVisible = false
  contextmenuX = 0
  contextmenuY = 0

  constructor (
    private _router: Router,
    private _funcs: Functions,
    private _store: Store<fromRoot.IState>
  ) { }

  ngOnInit () {
    // 获取待办清单
    this._store.select(fromRoot.selectChecklists)
      .subscribe((lists) => {
        this.menuItems = lists.map((list) => {
          const count = list.tasks.filter((u) => u.isDone === false).length
          list.unfinished = count
          return list
        })
      })
    this._store.select(fromRoot.selectTodayUnfinishedTasksCount)
      .subscribe((count) => this.unFinishedCount = count)
    // 获取登录用户信息
    this._store.select(fromRoot.selectUserEntity)
      .subscribe((user) => this.currentUser = user)
    // 初始化时获取当前路径 用于高亮对应的Menu
    this.currentUrl = this.getCurrentUrlWithoutQueryParams(this._router.url)
    // 发生路由跳转时更新currentUrl
    this._router.events.subscribe((event) => {
      if (event instanceof NavigationEnd) {
        this.currentUrl = this.getCurrentUrlWithoutQueryParams(event.urlAfterRedirects)
      }
    })
  }

  getCurrentUrlWithoutQueryParams (url) {
    const index = url.indexOf('?')
    return index === -1
      ? url
      : url.substring(0, index)
  }

  addList (): void {
    const newList: INewListDto = {
      title: '无标题清单',
      icon: 'list',
      userId: this.currentUser.id
    }
    this._store.dispatch(new fromChecklist.AddChecklistAction(newList))
  }

  isDefaultIcon (icon): boolean {
    return this._funcs.isDefaultIcon(icon)
  }

  handleContextmenu (e: MouseEvent, item) {
    this.contextmenuItem = item
    this.contextmenuVisible = true
    this.contextmenuX = e.clientX
    this.contextmenuY = e.clientY
    e.preventDefault()
  }

  @HostListener('document:click') closeContextmenu () {
    this.contextmenuVisible = false
  }

}
